<template>
  <page-header-wrapper>
    <a-card>
      <JeepaySearchForm :searchConditionNum="3" :searchFunc="searchFunc" :resetFunc="onReset">
        <a-form-item label="" class="table-search-item">
          <JeepayDateRangePicker ref="dateRangePicker" v-model:value="vdata.searchData['queryDateRange']" customDateRangeType="date" />
        </a-form-item>
        <jeepay-text-up v-model:value="vdata.searchData.qrcId" placeholder="码牌ID" />
        <jeepay-text-up v-model:value="vdata.searchData.appId" :placeholder="'应用AppId'" />
      </JeepaySearchForm>

      <!-- 列表渲染 -->
      <JeepayTable
        ref="infoTable"
        :reqTableDataFunc="reqTableDataFunc"
        :tableColumns="tableColumns"
        :searchData="vdata.searchData"
        rowKey="qrcId"
      >
        <template #topBtnSlot>
          <a-button v-if="$access('ENT_MCH_QR_CODE_ADD')" type="primary" @click="addOrEditFunc()"><PlusOutlined /> 新建</a-button>
          <a-button v-if="$access('ENT_MCH_QR_CODE_ADD')" type="primary" @click="showBind()"> 绑定二维码</a-button>
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'qrcId'">
            {{ record.qrcId }}
            <QrcodeOutlined style="font-size: 16px" @click="showQrImgFunc(record.qrcId)" />
          </template>

          <template v-if="column.key === 'qrcState'">
            <JeepayTableColState :state="record.qrcState" :showSwitchType="$access('ENT_MCH_QR_CODE_EDIT')" :onChange="(state) => { return updateState(record.qrcId, state)}" />
          </template>

          <template v-if="column.key === 'fixedFlag'">
            <span v-if="record.fixedFlag === 0">任意金额</span>
            <span v-else>{{ record.fixedPayAmount/100 }}</span>
          </template>

          <template v-if="column.key === 'op'">
            <!-- 操作列插槽 -->
            <JeepayTableColumns>
              <a-button v-if="$access('ENT_MCH_QR_CODE_VIEW')" type="link" @click="showQrImgFunc(record.qrcId)">详情</a-button>
              <a-button v-if="$access('ENT_MCH_QR_CODE_EDIT')" type="link" @click="addOrEditFunc(record.qrcId)">修改</a-button>
              <a-button v-if="$access('ENT_MCH_QR_CODE_EDIT') && record.qrcBelongType == 2 && record.bindState == 1 && (userStore.userInfo['userType'] != '11' && userStore.userInfo['userType'] != '12')" type="link" style="color: red" @click="unBindFunc(record.qrcId)">解绑</a-button>
              <a-button v-if="$access('ENT_MCH_QR_CODE_EDIT') && record.qrcBelongType == 2 && record.bindState == 1 && (userStore.userInfo['userType'] != '11' && userStore.userInfo['userType'] != '12')" type="link" @click="getBindDeviceFunc(record.qrcId)">受支持设备</a-button>
              <a-button v-if="$access('ENT_MCH_QR_CODE_DEL') && record.qrcBelongType == 1" type="link" style="color: red" @click="delFunc(record.qrcId)">删除</a-button>
            </JeepayTableColumns>
          </template>
        </template>
      </JeepayTable>

      <AddOrEdit ref="infoAddOrEdit" :callbackFunc="searchFunc" />
      <Bind ref="bindRef" :callbackFunc="searchFunc" />
      <JeepayQrcDeviceList ref="jeepayQrcDeviceListRef" sysType="MCH" />
    </a-card>
  </page-header-wrapper>
</template>
<script setup lang="ts">
import AddOrEdit from './AddOrEdit.vue'
import Bind from './Bind.vue'
import {API_URL_MCH_QR_CODE_LIST, req, reqLoad, $qrcShellViewByQrc, $unbindQrc} from '@/api/manage'
import { ref, reactive, getCurrentInstance } from 'vue'
import { useUserStore } from '@/store/modules/user'

// 导入全局函数
const { $infoBox, $access, $viewerApi } = getCurrentInstance()!.appContext.config.globalProperties

const userStore = useUserStore()
// infoTable组件
const infoTable = ref()

const infoAddOrEdit = ref()

const bindRef = ref()

const dateRangePicker = ref()

const jeepayQrcDeviceListRef = ref()

// eslint-disable-next-line no-unused-vars
const tableColumns = ref([
  { key: 'entryPage',  title: '获取方式', customRender: ({ record }) => {return record.qrcBelongType == 1 ? '自制' : '下发' }, },
  { key: 'entryPage',  title: '扫码页面', customRender: ({ record }) => {return record.entryPage == 'default' ? '默认' : record.entryPage == 'h5' ? 'H5' : '小程序'} ,},
  { key: 'qrcId', title: '二维码', },
  { key: 'qrcAlias', dataIndex: 'qrcAlias', title: '名称'},
  { title: '门店编号', dataIndex: 'storeId',  },
  { key: 'appId', dataIndex: 'appId', title: '应用ID', },
  { key: 'qrcState', title: '状态', },
  { key: 'fixedFlag', title: '固定金额', },
  { key: 'createdAt', dataIndex: 'createdAt', title: '创建日期', },
  { key: 'op', title: '操作', fixed: 'right', align: 'center', }
])


const vdata : any = reactive({
  searchData: {},

})

function searchFunc () {
  // vdata.btnLoading = true
  infoTable.value.refTable(true)
}
// 请求table接口数据
function reqTableDataFunc (params) {
  return req.list(API_URL_MCH_QR_CODE_LIST, params)
}


// 新增 or 修改函数
function addOrEditFunc(recordId?){
  infoAddOrEdit.value.show(recordId)
}


// 显示二维码图片
function showQrImgFunc(recordId){
  $qrcShellViewByQrc(recordId).then((res) => {
    $viewerApi({images: [res]})
  })
}

// 删除
function delFunc(recordId){
  $infoBox.confirmDanger('确认删除？', '', () => {
    req.delById(API_URL_MCH_QR_CODE_LIST, recordId).then(res => {
      $infoBox.message.success('删除成功')
      searchFunc()
    })
  })
}


function  updateState (recordId, state) { // 【更新状态】

  const title = state === 1 ? '确认[启用]？' : '确认[停用]？'
  return new Promise<void>((resolve, reject) => {
    $infoBox.confirmDanger(title, '', () => {
          return reqLoad.updateById(API_URL_MCH_QR_CODE_LIST, recordId, { qrcState: state }).then(res => {
            searchFunc()
            resolve()
          }).catch(err => reject(err))
        },
        () => {
          reject(new Error())
        })
  })
}
// 绑定码牌
function showBind() {
  bindRef.value.show()
}

// 解绑
function unBindFunc(recordId) {
  const title = '确认解绑？'
  const content = '解绑后商户将无法使用该码牌！'
  $infoBox.confirmDanger(title, content, () => {
    return $unbindQrc(recordId).then(res => {
      infoTable.value.refTable(true)
      $infoBox.message.success('解绑成功')
    })
  })
}

// 受支持的设备
function getBindDeviceFunc(recordId) {
  jeepayQrcDeviceListRef.value.show(recordId)
}

function onReset(){
  //重置搜索内容
  dateRangePicker.value.returnSelectModel()
  vdata.searchData = { queryDateRange: '' }
}
</script>
